package demo3;

class Money implements Cloneable{//表示Money支持克隆功能
    public double money=12.5;

    @Override
    protected Object clone() throws CloneNotSupportedException {//要重写克隆方法
        return super.clone();
    }
}

class Student implements Cloneable{//CloneNotSupportedException 必须实现Cloneable接口
    public int age;
    public Money m=new Money();

    public Student(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                '}';
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        /*        return super.clone();//Object中的clone方法使用了protected修饰，所以要重写，并用super访问
         */  Student tmp=(Student)super.clone();
        tmp.m=(Money)this.m.clone();
        return tmp;
    }
}


public class Test {
    public static void main(String[] args)  throws CloneNotSupportedException {
        Student student1=new Student(10);
        Student student2=(Student)student1.clone() ;//clone是父类方法，在子类中使用要强制转换 （向下转型）
        System.out.println(student1.m.money);//12.5
        System.out.println(student2.m.money);//12.5
        System.out.println("============");
        student2.m.money=100;
        System.out.println(student1.m.money);
        System.out.println(student2.m.money);
    }
}
